package cn.tedu.egnotice2.controller;

import ch.qos.logback.core.joran.util.beans.BeanUtil;
import cn.tedu.egnotice2.base.response.JsonResult;
import cn.tedu.egnotice2.base.response.StatusCode;
import cn.tedu.egnotice2.mapper.NoticeMapper;
import cn.tedu.egnotice2.pojo.dto.NoticeAddParam;
import cn.tedu.egnotice2.pojo.dto.NoticeAddQuery;
import cn.tedu.egnotice2.pojo.dto.NoticeUpdateParam;
import cn.tedu.egnotice2.pojo.entity.Notice;
import cn.tedu.egnotice2.pojo.vo.NoticeDetailInfoVO;
import cn.tedu.egnotice2.pojo.vo.NoticeListVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;

@Slf4j
@RestController
@RequestMapping("v1/notice/")
public class NoticeController {
    @Autowired
    private NoticeMapper noticeMapper;

    /**
     * 新增资讯
     * @param noticeAddParam
     * @return
     */
    @PostMapping("add")
    public JsonResult add(@RequestBody NoticeAddParam noticeAddParam){
    log.debug("noticeAddParam = " + noticeAddParam);
    Notice notice = new Notice();
    BeanUtils.copyProperties(noticeAddParam,notice);
    notice.setUserId(1L);
    notice.setCreateTime(new Date());
    notice.setUpdateTime(new Date());
    log.debug("notice = " + notice);
    noticeMapper.insertNotice(notice);
    return JsonResult.ok();
    }
    /**
     * 资讯列表
     */
    @GetMapping("list")
    public JsonResult list(@RequestBody NoticeAddQuery noticeAddQuery){
    log.debug("noticeAddQuery =" + noticeAddQuery);
    List<NoticeListVO> noticeListVO = noticeMapper.selectNoticeList(noticeAddQuery);
    return JsonResult.ok(noticeListVO);
    }
    /**
     * 资讯详情
     */
    @GetMapping("detail")
    public JsonResult detail(Long id){
        log.debug("id = " + id);
        NoticeDetailInfoVO noticeDetailInfoVO = noticeMapper.selectNoticeDetail(id);
        return JsonResult.ok(noticeDetailInfoVO);
    }

    /**
     * 删除资讯
     */
    @DeleteMapping("delete")
    public JsonResult delete(Long id){
        log.debug("id = " + id);
        int count = noticeMapper.deleteNotice(id);
        if (count > 0) {
            return JsonResult.ok();
        }
        return new JsonResult(StatusCode.FAILED);
    }
    /**
     * 修改资讯
     */
    @PostMapping("update")
    public JsonResult update(@RequestBody NoticeUpdateParam noticeUpdateParam){
        log.debug("noticeUpdateParam = " + noticeUpdateParam);
        Notice notice = new Notice();
        BeanUtils.copyProperties(noticeUpdateParam, notice);
        notice.setUpdateTime(new Date());
        int count = noticeMapper.updateNotice(notice);
        if (count > 0){
            return JsonResult.ok();
        }
        return new JsonResult(StatusCode.FAILED);
    }
}
